package com.example.netty.protocol;

import com.example.netty.callback.LongConnectEventCallback;
import com.example.netty.callback.SampleLongConnectEventCallback;
import com.example.netty.filter.Decoder;
import com.example.netty.filter.Encoder;
import com.example.netty.handler.SampleLongConnectNettyHandler;
import com.example.netty.options.SampleLongConnectNettyServerOptions;
import com.example.netty.service.LongConnectServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * 可以启动多个监听端口
 * @Auther Created by l.wang on 2019/5/29.
 */
@Component
public class SampleLongConnectNettyServerWrap implements LongConnectServer {
    private static Log log = LogFactory.getLog(SampleLongConnectNettyServerWrap.class);
    private final Executor executor = Executors.newSingleThreadExecutor();
    @Autowired
    private LongConnectEventCallback LongConnectEventCallback;
    /*@Autowired
    private TerminalContextService terminalContextService;*/

    private FutureTask<Void> task = null;
    @Autowired
    private Environment env;


    @Override
    public void start() {
        SampleLongConnectNettyServerOptions sampleLongConnectNettyServerOptions = new SampleLongConnectNettyServerOptions();
        sampleLongConnectNettyServerOptions.setPort(env.getProperty("tcpPort", Integer.class, 9999));
        sampleLongConnectNettyServerOptions.setIdleTimeout(env.getProperty("tcp.idleTimeout", Integer.class,60));
        sampleLongConnectNettyServerOptions.setReadIdleTimeout(env.getProperty("tcp.readIdleTimeout", Integer.class,10));
        sampleLongConnectNettyServerOptions.setWriteIdleTimeout(env.getProperty("tcp.writeIdleTimeout", Integer.class,10));
        task = new FutureTask<>(new SampleLongConnectNettyServer(sampleLongConnectNettyServerOptions, LongConnectEventCallback), null);
        executor.execute(task);
    }

    @Override
    public void stop() {
        if (task != null)
            task.cancel(true);
    }

    class SampleLongConnectNettyServer implements Runnable {
        private SampleLongConnectNettyServerOptions serverOptions;
        private SampleLongConnectEventCallback callback;

        public SampleLongConnectNettyServer(SampleLongConnectNettyServerOptions sampleLongConnectNettyServerOptions,
                                               LongConnectEventCallback LongConnectEventCallback) {
            this.serverOptions = sampleLongConnectNettyServerOptions;
            this.callback = LongConnectEventCallback;
        }

        /**
         * 启动服务
         *
         * @throws InterruptedException
         */
        private void startServer() throws InterruptedException {
            int idleTimeout = serverOptions.getIdleTimeout();
            int readIdleTimeout = serverOptions.getReadIdleTimeout();
            int writeIdleTimeout = serverOptions.getWriteIdleTimeout();
            int port = serverOptions.getPort();

            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workGroup = new NioEventLoopGroup();

            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("idleStateHandler", new IdleStateHandler(readIdleTimeout, writeIdleTimeout, idleTimeout));
//                            pipeline.addLast(new NoLoginDisconnectHandler(5, TimeUnit.MINUTES, terminalContextService)); //未登录处理
                            /**自定义编码器/解码器**/
                            pipeline.addLast(new Decoder());
                            pipeline.addLast(new Encoder());
                            /**添加多个过滤器解码**/
                            /*pipeline.addLast(new HexStringForByteBufDecoder()); //先将十六进制字符串解成byte[]数组
                            pipeline.addLast(new BinaryFrameDecoder());//解包byte[]数组
                            pipeline.addLast(new StringEncoder());//发送己转成十六进制字符串
                            pipeline.addLast(new HexStringForByteBufEncoder());//将byte[]数组转成十六进制字符串*/
                            pipeline.addLast(new SampleLongConnectNettyHandler(callback));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 512)
                    .option(EpollChannelOption.TCP_KEEPINTVL, 10)
                    .option(EpollChannelOption.TCP_KEEPCNT, 3)
                    .option(EpollChannelOption.TCP_KEEPIDLE, 30)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();

            log.info("start success");

            f.channel().closeFuture().syncUninterruptibly();
        }

        @Override
        public void run() {
            try {
                startServer();
            } catch (Exception e) {
                log.error("start is failed", e);
            }
        }
    }
}